//
//  DDPictureBrowserVC.swift
//  SinaMicroBlogSwift2
//
//  Created by dqw on 15/8/9.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import  SVProgressHUD

private let DDPictureBrowserCellID = "DDPictureBrowserCellID"
class DDPictureBrowserVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    var index: Int?
    var imageUrls: [NSURL]?
    
    init(index: Int, imageUrls: [NSURL]) {
        self.index = index
        self.imageUrls = imageUrls
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func loadView() {
         super.loadView()
        
        var s = view.frame.size
        s.width += 20.0
        view.frame.size = s
        
        
        
        configureCollectionView()
        configureButton()
        
    }
//    prviate func changeView() {
//        let vw = UIView()
//        
//    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        xx()
        print("will")
    }
    private func xx() {
        let indexPath = NSIndexPath(forItem: index!, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
//        xx()
        print("did")
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
//        xx()
        print("lay")
    }
    
    // 布局collectionView
    private func configureCollectionView() {
        view.addSubview(collectionView)
        collectionView.frame  = view.bounds
        collectionView.dataSource = self
        collectionView.registerClass(DDPictureBrowserCell.self, forCellWithReuseIdentifier: DDPictureBrowserCellID)
        
        let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
//        flowLayout.itemSize = UIScreen.mainScreen().bounds.size
        flowLayout.itemSize = view.frame.size
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView.pagingEnabled = true
    }
    // 布局按钮。
    private func configureButton() {
        // 添加控件
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        // 布局控件
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        let dict = ["cl": closeButton, "sv": saveButton]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-50-[cl]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cl]-50-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[sv]-50-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[sv]-50-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveButton.addTarget(self, action: "savePicture", forControlEvents: UIControlEvents.TouchUpInside)
    }
    func savePicture() {
       let  cell = collectionView.visibleCells().last as! DDPictureBrowserCell

        if  let image = cell.imageView.image {
            UIImageWriteToSavedPhotosAlbum(image, self, "image: didFinishSavingWithError: contextInfo:", nil)
        }
//        - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    }
    func image(image: UIImage, didFinishSavingWithError error: NSError?,  contextInfo: AnyObject?) {
        let msg = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(msg)
    }
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }

    // MARK: -  懒加载
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var closeButton: UIButton = UIButton(title: "关闭", imageName: nil)
    private lazy var saveButton: UIButton = UIButton(title: "保存", imageName: nil)
    
    func currentImageView(indexPath: NSIndexPath) -> UIImageView {
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! DDPictureBrowserCell
        return cell.imageView
    }
    func currentIndexPath() -> NSIndexPath {
        let cell = collectionView.visibleCells().last
        return collectionView.indexPathForCell(cell!)!
    }
    var imageViewScale: CGFloat = 1
}


//     MARK: - 数据源方法
extension DDPictureBrowserVC: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (imageUrls?.count)!
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(DDPictureBrowserCellID, forIndexPath: indexPath) as! DDPictureBrowserCell
            cell.imageUrl = imageUrls![indexPath.item]
            cell.backgroundColor = UIColor.blackColor()
            cell.delegate = self
        
            return cell
    }
}
extension DDPictureBrowserVC: DDScrollViewZoomDelegate {
    func didZoom(scale: CGFloat) {
        hiddenSubviews(scale < 1)
        imageViewScale = scale
        if scale < 1 {
            startInteractiveTransition(self)
        }else {
            view.transform = CGAffineTransformIdentity
            view.alpha = 1
        }
    }
    
    func endZoom(scale: CGFloat) {
        if scale < 0.8 {
        completeTransition(true)
        }else {
            UIView.animateWithDuration(0.5, animations: { () -> Void in
               self.view.transform = CGAffineTransformIdentity
                self.currentImageView(self.currentIndexPath()).transform = CGAffineTransformIdentity
                self.view.alpha = 1
                }, completion: { (_ ) -> Void in
                    self.hiddenSubviews(false)
            })
        }
    }
  
    func hiddenSubviews(isHidden:Bool) {
        collectionView.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
        closeButton.hidden = isHidden
        saveButton.hidden = isHidden
    }
}
extension DDPictureBrowserVC: UIViewControllerInteractiveTransitioning {
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        view.transform = CGAffineTransformMakeScale(imageViewScale, imageViewScale)
        view.alpha = imageViewScale
    }
}
extension DDPictureBrowserVC: UIViewControllerContextTransitioning {
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func containerView() -> UIView? {
        return view.superview
    }
    func isAnimated() -> Bool {
        return true
    }
    func isInteractive() -> Bool {
        return true
    }
    func transitionWasCancelled() -> Bool {
        return false
    }
    func presentationStyle() -> UIModalPresentationStyle {
            return UIModalPresentationStyle.Custom
    }
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    
    func viewControllerForKey(key: String) -> UIViewController? {
        return self
    }
    func viewForKey(key: String) -> UIView? {return view}
    func targetTransform() -> CGAffineTransform {
        return CGAffineTransformIdentity
    }
    func initialFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }
    func finalFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }
}


